<template>
  <view class="order-edit">
    <view class="top-bg"></view>
    <!-- 导航栏 -->
    <s-nav-bar title="修改订单" :background="'transparent'" :titleStyle="{ color: '#ffffff', fontWeight: 'bold' }" statusBar
      back :backStyle="{ color: '#ffffff' }">
      <view slot="right" @click="showDeleteConfirm">
        <s-icon name="delete" color="#fff" size="20"></s-icon>
      </view>
    </s-nav-bar>

    <!-- 表单内容 -->
    <scroll-view class="main-scroll" scroll-x="false" scroll-y="true">
      <view class="form-container">
        <!-- 客户信息 -->
        <view class="form-section">
          <view class="section-header">
            <view class="header-line"></view>
            <text class="header-text">客户信息</text>
          </view>

          <view class="form-item">
            <text class="item-label required">客户姓名</text>
            <input v-model="formData.customer_name" class="item-input" placeholder="请输入客户姓名"
              placeholder-class="placeholder" maxlength="20" />
          </view>

          <view class="form-item">
            <text class="item-label required">联系方式</text>
            <input v-model="formData.phone" class="item-input" type="tel" placeholder="请输入手机号码"
              placeholder-class="placeholder" maxlength="11" />
          </view>
        </view>

        <!-- 订单信息 -->
        <view class="form-section">
          <view class="section-header">
            <view class="header-line"></view>
            <text class="header-text">订单信息</text>
          </view>

          <view class="form-item">
            <text class="item-label required">服务类型</text>
            <view class="radio-group">
              <view class="radio-item" :class="{ active: formData.type === item.name }" @click="formData.type = item.name"
                v-for="(item, index) in typeList" :key="index">
                {{ item.name }}
              </view>
              <view class="link" @click="goCateManage"><s-icon name="label-o"></s-icon>管理分类</view>
            </view>
          </view>

          <view class="form-item">
            <text class="item-label required">开始日期</text>
            <picker mode="date" :value="formData.start_date" :start="minDate" @change="bindStartDateChange">
              <view class="picker-item">
                <text :class="{ placeholder: !formData.start_date }">
                  {{ formData.start_date || "请选择开始日期" }}
                </text>
                <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="item-label required">结束日期</text>
            <picker mode="date" :value="formData.end_date" :start="formData.start_date || minDate"
              @change="bindEndDateChange">
              <view class="picker-item">
                <text :class="{ placeholder: !formData.end_date }">
                  {{
                    formData.end_date ||
                    (formData.start_date ? "同开始日期" : "请选择结束日期")
                  }}
                </text>
                <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
              </view>
            </picker>
          </view>

          <!-- 订单渠道 -->
          <view class="form-item">
            <text class="item-label">订单渠道</text>
            <view class="radio-group with-input">
              <view class="radio-item" :class="{ active: formData.channel === '线上' }"
                @click="formData.channel = '线上'; customChannel = ''">
                线上
              </view>
              <view class="radio-item" :class="{ active: formData.channel === '线下' }"
                @click="formData.channel = '线下'; customChannel = ''">
                线下
              </view>
              <view class="radio-item" :class="{ active: formData.channel === '门店' }"
                @click="formData.channel = '门店'; customChannel = ''">
                门店
              </view>
              <input v-model="customChannel" class="small-input" :class="{ 'custom-active': isCustomChannel }"
                placeholder="其他" placeholder-class="placeholder" maxlength="4" @focus="handleChannelFocus" />
              <view class="link" @click="goChannelManage"><s-icon name="label-o"></s-icon>管理渠道</view>
            </view>
          </view>

          <view class="form-item">
            <text class="item-label">备注</text>
            <view class="input-with-unit">
              <textarea v-model="formData.note" class="item-input" placeholder="请输入备注" placeholder-class="placeholder" />
            </view>
          </view>
        </view>

        <!-- 财务信息 -->
        <view class="form-section">
          <view class="section-header">
            <view class="header-line"></view>
            <text class="header-text">财务信息</text>
          </view>

          <view class="form-item">
            <text class="item-label">已收金额</text>
            <view class="input-with-unit">
              <input v-model="formData.deposit" class="item-input" type="digit" placeholder="请输入金额"
                placeholder-class="placeholder" @input="formatAmount('deposit')" />
              <text class="unit">元</text>
            </view>
          </view>

          <view class="form-item">
            <text class="item-label">尾款</text>
            <view class="input-with-unit">
              <input v-model="formData.final_payment" class="item-input" type="digit" placeholder="请输入金额"
                placeholder-class="placeholder" @input="formatAmount('final_payment')" />
              <text class="unit">元</text>
            </view>
          </view>

          <view class="form-item amount-item">
            <text class="item-label">总金额</text>
            <text class="amount">{{ totalAmount }} 元</text>
          </view>

          <!-- 支付方式 -->
          <view class="form-item">
            <text class="item-label">支付方式</text>
            <view class="radio-group with-input">
              <view class="radio-item" :class="{ active: formData.payment_method === '微信' }"
                @click="formData.payment_method = '微信'; customPaymentMethod = ''">
                微信
              </view>
              <view class="radio-item" :class="{ active: formData.payment_method === '公账' }"
                @click="formData.payment_method = '公账'; customPaymentMethod = ''">
                公账
              </view>
              <view class="link" @click="goPaymentManage"><s-icon name="label-o"></s-icon>管理支付方式</view>
              <input v-model="customPaymentMethod" class="small-input" :class="{ 'custom-active': isCustomPayment }"
                placeholder="其他" placeholder-class="placeholder" maxlength="4" @focus="handlePaymentFocus" />
            </view>
          </view>

          <view class="form-item">
            <text class="item-label">订单状态</text>
            <view class="radio-group">
              <view class="radio-item" :class="{ active: formData.status === '1' }" @click="formData.status = '1'">
                启用
              </view>
              <view class="radio-item" :class="{ active: formData.status === '0' }" @click="formData.status = '0'">
                禁用
              </view>
            </view>
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="submit-btn">
          <button class="submit-button" :disabled="isSubmitting" @click="submitForm">
            <text v-if="!isSubmitting">保存修改</text>
            <text v-else>提交中...</text>
          </button>
        </view>
      </view>
    </scroll-view>

    <!-- 员工选择弹窗 -->
    <staff-selector v-model="showStaffSelect" :staff-list="staffList" :selected-staff="selectedStaff" :multiple="true"
      @confirm="handleStaffConfirm" />
    <s-dialog></s-dialog>

  </view>
</template>

<script>
import Dialog from '@/uni_modules/s-ui/utils/dialog';

export default {
  data() {
    const today = new Date();
    const minDate = `${today.getFullYear()}-${String(
      today.getMonth() + 1
    ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

    return {
      orderId: null,
      typeList: [],
      staffList: [],
      selectedStaff: [],
      showStaffSelect: false,
      formData: {
        customer_name: "",
        phone: "",
        type: "",
        start_date: "",
        end_date: "",
        channel: "线上",
        deposit: "",
        note: "",
        final_payment: "",
        payment_method: "微信",
        status: "1",
        member_id: "",
        member_name: ""
      },
      customChannel: "",
      customPaymentMethod: "",
      minDate: minDate,
      isSubmitting: false,
    };
  },
  computed: {
    totalAmount() {
      const deposit = parseFloat(this.formData.deposit) || 0;
      const finalPayment = parseFloat(this.formData.final_payment) || 0;
      return (deposit + finalPayment).toFixed(2);
    },
    // 判断是否是自定义渠道
    isCustomChannel() {
      return this.customChannel && !['线上', '线下', '门店'].includes(this.formData.channel);
    },
    // 判断是否是自定义支付方式
    isCustomPayment() {
      return this.customPaymentMethod && !['微信', '公账'].includes(this.formData.payment_method);
    }
  },
  onLoad(options) {
    if (options.id) {
      this.orderId = options.id;
      this.getOrderDetail();
    }
    this.getTypeList();
    this.getStaffList();
  },
  methods: {
    // 使用带斜杠前缀的绝对路径修复导航
    goCateManage() {
      uni.navigateTo({ url: '/pages/extra/category/index' })
    },
    
    // 使用带斜杠前缀的绝对路径修复导航
    goChannelManage() {
      uni.navigateTo({ url: '/pages/extra/source/index' })
    },
    
    // 使用带斜杠前缀的绝对路径修复导航
    goPaymentManage() {
      uni.navigateTo({ url: '/pages/extra/payMethod/index' })
    },
    // 获取订单详情
    getOrderDetail() {
      this.sjuAjax.get("/order/detail", { id: this.orderId }, (res) => {
        if (res && res.code === 200) {
          // 将接口返回的数据映射到表单
          const orderData = res.data;
          this.formData = {
            customer_name: orderData.customer_name || "",
            phone: orderData.phone || "",
            type: orderData.type || "",
            start_date: orderData.start_date || "",
            end_date: orderData.end_date || "",
            channel: orderData.channel || "线上",
            deposit: orderData.deposit || "",
            final_payment: orderData.final_payment || "",
            payment_method: orderData.payment_method || "微信",
            status: orderData.status || "1",
            member_id: orderData.member_id || "",
            member_name: orderData.member_name || "",
            note: orderData.note || ""
          };

          // 检查是否是自定义渠道或支付方式
          if (orderData.channel && !['线上', '线下', '门店'].includes(orderData.channel)) {
            this.customChannel = orderData.channel;
          }
          if (orderData.payment_method && !['微信', '公账'].includes(orderData.payment_method)) {
            this.customPaymentMethod = orderData.payment_method;
          }
        }
      });
    },

    // 获取服务类型列表
    getTypeList() {
      this.sjuAjax.get("/category/list", {}, (res) => {
        if (res && res.code === 200) {
          this.typeList = res?.data?.list || res?.data;
        }
      });
    },

    // 获取员工列表
    getStaffList() {
      this.sjuAjax.get("/member/list", {}, (res) => {
        if (res && res.code === 200) {
          this.staffList = res.data?.list || [];
        }
      });
    },

    bindStartDateChange(e) {
      this.formData.start_date = e.detail.value;
      if (!this.formData.end_date || this.formData.end_date < e.detail.value) {
        this.formData.end_date = e.detail.value;
      }
    },

    bindEndDateChange(e) {
      this.formData.end_date = e.detail.value;
    },

    showStaffPopup() {
      this.showStaffSelect = true;
    },

    handleChannelFocus() {
      this.formData.channel = '';
    },

    handlePaymentFocus() {
      this.formData.payment_method = '';
    },

    handleStaffConfirm(selected) {
      this.selectedStaff = selected;
      if (selected.length > 0) {
        this.formData.member_id = selected.map(staff => staff.id).join(',');
        this.formData.member_name = selected.map(staff => staff.real_name).join('、');
      } else {
        this.formData.member_id = '';
        this.formData.member_name = '';
      }
    },

    formatAmount(field) {
      let value = this.formData[field];
      value = value.replace(/[^\d.]/g, "");
      const parts = value.split(".");
      if (parts.length > 2) {
        value = parts[0] + "." + parts.slice(1).join("");
      }
      if (parts.length === 2 && parts[1].length > 2) {
        value = parts[0] + "." + parts[1].substring(0, 2);
      }
      this.formData[field] = value;
    },

    validateForm() {
      if (!this.formData.customer_name) {
        uni.showToast({ title: "请填写客户姓名", icon: "none" });
        return false;
      }

      if (!this.formData.phone) {
        uni.showToast({ title: "请填写联系方式", icon: "none" });
        return false;
      }

      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({ title: "请输入正确的手机号", icon: "none" });
        return false;
      }

      if (!this.formData.type) {
        uni.showToast({ title: "请选择服务类型", icon: "none" });
        return false;
      }

      if (!this.formData.start_date) {
        uni.showToast({ title: "请选择开始日期", icon: "none" });
        return false;
      }

      if (!this.formData.end_date) {
        uni.showToast({ title: "请选择结束日期", icon: "none" });
        return false;
      }

      return true;
    },

    // 显示删除确认对话框
    showDeleteConfirm() {
      Dialog({
        title: "删除订单",
        message: "确定要删除该订单吗？\n删除后不可恢复！"
      }).then(() => {
        this.deleteOrder();
      }).catch(() => {
        // 取消操作
      });
    },

    // 删除订单
    deleteOrder() {
      this.sjuAjax.post("/order/delete", { id: this.orderId }, (res) => {
        if (res && res.code === 200) {
          uni.showToast({
            title: "删除成功",
            icon: "success",
            duration: 2000,
          });

          setTimeout(() => {
            // 直接跳转到订单列表页面，确保页面刷新
            uni.reLaunch({
              url: '/pages/order/list'
            });
          }, 1500);
        }
      });
    },

    // 提交表单
    submitForm() {
      if (!this.validateForm()) return;

      this.isSubmitting = true;

      // 处理自定义渠道和支付方式
      if (this.customChannel && !['线上', '线下', '门店'].includes(this.formData.channel)) {
        this.formData.channel = this.customChannel;
      }
      if (this.customPaymentMethod && !['微信', '公账'].includes(this.formData.payment_method)) {
        this.formData.payment_method = this.customPaymentMethod;
      }

      const postData = {
        id: this.orderId,
        ...this.formData,
        deposit: parseFloat(this.formData.deposit) || 0,
        final_payment: parseFloat(this.formData.final_payment) || 0,
      };

      this.sjuAjax.post("/order/update", postData, (res) => {
        this.isSubmitting = false;
        if (res.code === 200) {
          uni.showToast({
            title: "修改成功",
            icon: "success",
            duration: 2000,
          });

          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || "修改失败",
            icon: "none",
            duration: 2000,
          });
        }
      }, () => {
        this.isSubmitting = false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.order-edit {
  background-color: var(--v-bg);
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top-bg {
  width: 100%;
  height: 312rpx;
  border-radius: 0 0 24rpx 24rpx;
  background: var(--v-linear);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 0;
}

.main-scroll {
  flex-grow: 1;
  height: 0;
}

.form-container {
  padding: 30rpx;
  opacity: 0.97;
}

.form-section {
  background-color: #fff;
  margin-bottom: 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: var(--v-shadow);
}

.section-header {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  border-bottom: 2rpx solid #f1f1f1;
}

.header-line {
  width: 8rpx;
  height: 32rpx;
  background-color: var(--v-theme);
  margin-right: 20rpx;
  border-radius: 4rpx;
}

.header-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.form-item {
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.item-label {
  display: block;
  margin-bottom: 20rpx;
  font-size: 28rpx;
  color: #666;
}

.item-label.required::after {
  content: "*";
  color: #f56c6c;
  margin-left: 8rpx;
}

.item-input {
  width: 100%;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;

  >* {
    margin-right: 20rpx;
    /* Replaced gap: 20rpx */
    margin-bottom: 20rpx;

    &:last-child {
      margin-right: 0;
      /* Remove margin from last child */
    }
  }
}

.radio-group.with-input {
  align-items: center;
}

.radio-item {
  padding: 16rpx 30rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
}

.picker-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
}

.input-with-unit {
  display: flex;
  align-items: center;
}

.input-with-unit .item-input {
  flex: 1;
}

.unit {
  width: 60rpx;
  text-align: center;
  font-size: 28rpx;
  color: #999;
}

.small-input {
  width: 120rpx;
  height: 60rpx;
  padding: 0 10rpx;
  border: 2rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #333;
  text-align: center;

  &:focus {
    border-color: var(--v-theme);
  }
}

/* 自定义输入框高亮样式 */
.custom-active {
  border-color: var(--v-theme) !important;
  background-color: rgba(var(--v-theme-rgb), 0.1) !important;
  color: var(--v-theme) !important;
}

.custom-active::placeholder {
  color: var(--v-theme) !important;
  opacity: 0.6;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount {
  font-size: 32rpx;
  font-weight: bold;
  color: var(--v-theme);
}

.submit-btn {
  padding: 30rpx;
  padding-bottom: 40rpx;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: var(--v-linear);
  color: #fff;
  border-radius: 8rpx;
  font-size: 32rpx;
}

.placeholder {
  color: #999;
}

.active {
  background-color: var(--v-theme);
  color: #fff;
  border-color: var(--v-theme);
}

.link {
  padding-left: 16rpx;
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: var(--v-theme);

  >* {
    margin-right: 9rpx;

    /* Replaced gap: 9rpx */
    &:last-child {
      margin-right: 0;
      /* Remove margin from last child */
    }
  }
}
</style>